//
//  UISearchBarWithSpinner.m
//  YoucApp
//
//  Created by Liam on 12/8/12.
//
//

#import "SearchBarWithActivity.h"

@interface SearchBarWithActivity ()

@property (retain) UIActivityIndicatorView *activityIndicatorView;

@end

@implementation SearchBarWithActivity

@synthesize activityIndicatorView = _activityIndicatorView;

- (id)initWithFrame:(CGRect)frame
{
	self = [super initWithFrame:frame];
	
	if (self)
	{
		self.tintColor = [UIColor whiteColor];
		self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"wy_search_bg.png"]];
	}
	
	return self;
}

- (void)layoutSubviews {

    [super layoutSubviews];
	
	for (id subview in self.subviews)
	{
		if ([subview isKindOfClass:[UIButton class]]) {
			[subview setEnabled:YES];
			[subview setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
		}
		if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
			[subview setHidden:YES];
		}
	}
}

- (void)initActivity
{
	if (!self.activityIndicatorView)
	{
		UIActivityIndicatorView *taiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
		
		taiv.hidesWhenStopped = YES;
		taiv.backgroundColor = [UIColor whiteColor];
		self.activityIndicatorView = taiv;
		[taiv release];
		
		UIButton *clearButton = nil;
		UITextField *searchField = nil;
		
		for(UIView* view in self.subviews)
		{
			if([view isKindOfClass:[UITextField class]])
			{
				searchField = (UITextField *)view;
				for(UIView* subView in searchField.subviews)
				{
					if([subView isKindOfClass:[UIButton class]])
					{
						clearButton = (UIButton *)subView;
						break;
					}
				}
				break;
			}
		}
		
		if (clearButton)
			[clearButton addSubview:self.activityIndicatorView];
		else if (searchField.leftView)
			[searchField.leftView addSubview:self.activityIndicatorView];
	}
}

- (void)startActivity
{
	[self initActivity];
	
	[self setNeedsLayout];
	
	[self.activityIndicatorView startAnimating];
}

- (void)finishActivity
{
	[self.activityIndicatorView stopAnimating];
}

- (void)cancel
{
	for (UIView *subView in self.subviews)
	{
		if([subView isKindOfClass:UIButton.class])
		{
			UIButton *cancelButton = (UIButton*)subView;
			[cancelButton sendActionsForControlEvents: UIControlEventTouchUpInside];
			break;
		}
	}
}

- (void)dealloc {
    SAFE_RELEASE(_activityIndicatorView);
    [super dealloc];
}

@end
